package com.lgc.demo.linklist;

public class ReverseLink {
    /**
     * 反转单链表
     *
     * @param args
     */
    public static void main(String[] args) {
        Node node4 = new Node();
        node4.setValue(4);
        node4.setNext(null);

        Node node3 = new Node();
        node3.setValue(3);
        node3.setNext(node4);

        Node node2 = new Node();
        node2.setValue(2);
        node2.setNext(node3);

        Node node1 = new Node();
        node1.setValue(1);
        node1.setNext(node2);

        Node head = node1;
        writeLink(head);

        head = reverse(head);

        writeLink(head);

        int a = 0;
    }

    private static void writeLink(Node head) {
        while (head != null) {
            System.out.println(head.getValue());
            head = head.getNext();
        }
    }

    private static Node reverse(Node head) {
        if (head == null) {
            return head;
        }

        //上一节点
        Node pre = head;
        //当前节点
        Node curr = head.getNext();
        //用于存储下一节点
        Node temp;

        //curr==null即尾节点
        while (curr != null) {
            //下一节点存入临时节点
            temp = curr.getNext();

            curr.setNext(pre);

            //移动指针
            pre = curr;
            curr = temp;
        }

        head.setNext(null);

        return pre;
    }
}
